package standard

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"net"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"
)

func DoPrint() {
	fmt.Println("my is println")
	fmt.Printf("%s\n", "good body")
}

func CreateFile() {
	f, err := os.Create("d:/test.txt")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer func(f *os.File) {
		err := f.Close()
		if err != nil {
			fmt.Println("Close fail", err.Error())
		}
	}(f)

	length, err := f.WriteString("my create file")
	if err != nil {
		fmt.Println("write error", err.Error())
		return
	}
	fmt.Printf("length = %d\n", length)

}

func DoConverter() {
	num := 90
	str := strconv.Itoa(num)
	fmt.Println("字符串形式的数字:", str)

	str = "50"
	num, err := strconv.Atoi(str)
	if err != nil {
		fmt.Println("Atoi fail", err.Error())
		return
	}
	fmt.Println("num =", num)
}

func DoThread() {
	var wg sync.WaitGroup
	wg.Add(2)

	go func() {
		fmt.Println("task1 is finish")
		wg.Done()
	}()

	go func() {
		fmt.Println("task2 is finish")
		wg.Done()
	}()

	wg.Wait()
	fmt.Println("all task is finish")
}

func DoTime() {
	var now time.Time
	now = time.Now()
	fmt.Println("now =", now)

	format := "2006-01-02 15:04:05"
	str := now.Format(format)
	fmt.Println("格式化后的时间:", str)

	str = "2023-04-25 12:00:00"
	t, err := time.Parse(format, str)
	if err != nil {
		fmt.Println("解析时间失败:", err.Error())
		return
	}
	fmt.Println("解析后的时间:", t)

}

func DoNet() {
	ip, err := net.ResolveIPAddr("ip", "www.baidu.com")
	if err != nil {
		fmt.Println("doNet fail", err.Error())
		return
	}
	fmt.Println("ip =", ip)
}

func DoMD5() {
	h := md5.New()
	length, err := io.WriteString(h, "md5 加密测试！")
	if err != nil {
		fmt.Println("WriteString fail", err.Error())
		return
	}
	fmt.Println("length =", length)
	fmt.Printf("%x\n", h.Sum(nil))
	fmt.Printf("%X\n", h.Sum(nil)) // 大写的 X，代表大写的十六进制字符串

	hh := md5.New()
	hh.Write([]byte("md5 加密测试！"))
	fmt.Println(hex.EncodeToString(hh.Sum(nil)) + "")
	fmt.Println(strings.ToTitle(hex.EncodeToString(hh.Sum(nil)))) // strings.ToTitle() 转大写
}

func MD5One() {
	md5New := md5.New()
	md5New.Write([]byte("123456"))
	// hex转字符串
	md5String := hex.EncodeToString(md5New.Sum(nil))
	fmt.Println(md5String)
	// e10adc3949ba59abbe56e057f20f883e
}

func MD5Two() {
	h := md5.New()
	_, err := io.WriteString(h, "123456")
	if err != nil {
		return
	}
	sum := h.Sum(nil)
	fmt.Println(hex.EncodeToString(sum[:]))
	// e10adc3949ba59abbe56e057f20f883e
}

func MD5Three() {
	data := []byte("123456")
	sum := md5.Sum(data)
	// hex转字符串
	md5String := hex.EncodeToString(sum[:])
	fmt.Println(md5String)
	// e10adc3949ba59abbe56e057f20f883e
	// 同
	fmt.Printf("%x", md5.Sum(data))
}
